//
// Created by yan on 6/29/17.
//

#include "sys/bSysComposit.h"
#include <unistd.h>
#include <signal.h>
#include <algorithm>
using namespace std;
typedef pair<std::string ,bSysNode*> mpair;
void *thr_fn(void *arg)
{
    if(arg == NULL)
    {
        cout << "thread arg get failed" << endl;
        return (void *)0;
    }
    auto p = (bSysNode **)(arg);
    auto sys = *p;
    (sys)->start();


    return ( (void*)100);
}



bSysComposit::bSysComposit() {
    pList = new std::map<std::string ,bSysNode*>;
}

void bSysComposit::Add(bSysNode *node) {
    m_sNode.push_back(node);

    pList->insert(mpair(node->getNodeName(),node));
}

void bSysComposit::Remove(bSysNode *node) {

}

int bSysComposit::initcfg() {

    class initNode{
    public:
        initNode(map<std::string ,bSysNode*> * mlist) : list(mlist){}
        void operator()(bSysNode * node){
            node->setpList(list);
            node->initcfg();
        }

    private:
        map<std::string ,bSysNode*> * list;
    };

    for_each(m_sNode.begin(),m_sNode.end(),initNode(pList));
    return bSysNode::initcfg();
}

int bSysComposit::start() {

    class startTask{
    public:
        startTask(){};
        void operator() (bSysNode * node){
            pthread_t ntid;
            pthread_create(&ntid,NULL,thr_fn,(&node));
            ntidgroup.push_back(ntid);
            sleep(1);
        }

        operator vector<pthread_t> () {
            return ntidgroup;
        }

    private:
        vector<pthread_t> ntidgroup;

    };

    vector<pthread_t> pidg = for_each(m_sNode.begin(),m_sNode.end(),startTask());

    for_each(pidg.begin(),pidg.end(),[](pthread_t m_pid){
        pthread_join(m_pid,NULL);
    });

    return bSysNode::start();;
}

int bSysComposit::end() {
    return bSysNode::end();
}

int bSysComposit::wait() {
    signal(SIGINT, stop);
    while(stopsign){
        sleep(2);
    }
    return 0;
}
int bSysComposit::stopsign = 1 ;
void bSysComposit::stop(int) {
    cout << "stop !!" <<endl;
    stopsign = 0;

}





